package cn.kgc.utils;

import cn.kgc.reflect.Person;
import cn.kgc.reflect.Student;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/2/15
 * @Description:
 */
public class NewBeanFactory {

    private static Map<String,Object> container = new HashMap<>();

    static {
        InputStream resourceAsStream = NewBeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");

        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
            Enumeration<Object> keys = properties.keys();
            while (keys.hasMoreElements()){
                String key = (String) keys.nextElement();
                String val = (String) properties.get(key);  // cn.kgc.reflect.Person

                Class<?> clazz = Class.forName(val);
                Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
                declaredConstructor.setAccessible(true);
                Object obj = declaredConstructor.newInstance();


                container.put(key, obj);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    public static Object  getBean(String beanName){
        return container.get(beanName);
    }



    public static <T> T getBean(String beanName,Class<T> clazz){

        Object o = container.get(beanName);
        return clazz.cast(o);
    }


    public static void main(String[] args) {

        //Object student1 = NewBeanFactory.getBean("student");
        //Student student2 = (Student) NewBeanFactory.getBean("student");
        //System.out.println(student1==student2);   // 单例

        Person person = NewBeanFactory.getBean("person", Person.class);
        System.out.println("person = " + person);



    }

}
